import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { componentRegistry } from '../utils/ComponentRegistry'

export const useLowCodeStore = defineStore('lowcode', () => {
  // 状态定义
  const components = ref(componentRegistry.getAll())
  const previewComponents = ref([])
  const nowComponent = ref({})
  const history = ref([])
  const historyIndex = ref(-1)
  const pageConfig = ref({ title: '未命名页面' })

  // 计算属性
  const canUndo = computed(() => historyIndex.value > 0)
  const canRedo = computed(() => historyIndex.value < history.value.length - 1)

  // 按分类获取组件
  const getComponentsByCategory = (category) => {
    return components.value.filter((item) => item.category === category)
  }

  // actions

  function nowComponentsData(value) {
    nowComponent.value = value
  }

  function updateNowComponents(value) {
    nowComponent.value = value
    const index = previewComponents.value.findIndex((item) => item.id === value.id)
    if (index !== -1) {
      previewComponents.value[index] = value
      addHistory()
    }
  }

  // 添加组件删除功能
  function deleteComponent(id) {
    const index = previewComponents.value.findIndex((item) => item.id === id)
    if (index !== -1) {
      previewComponents.value.splice(index, 1)

      // 如果删除的是当前选中的组件，清空选中状态
      if (nowComponent.value.id === id) {
        nowComponent.value = {}
      }

      addHistory()
    }
  }

  // 历史记录相关功能
  function addHistory() {
    // 如果不是在最新状态下的操作，需要截断历史记录
    if (historyIndex.value < history.value.length - 1) {
      history.value = history.value.slice(0, historyIndex.value + 1)
    }

    // 保存当前状态的深拷贝
    history.value.push(
      JSON.stringify({
        previewComponents: previewComponents.value,
        pageConfig: pageConfig.value,
      }),
    )

    historyIndex.value = history.value.length - 1
  }

  function undo() {
    if (canUndo.value) {
      historyIndex.value--
      const state = JSON.parse(history.value[historyIndex.value])
      previewComponents.value = state.previewComponents
      pageConfig.value = state.pageConfig
    }
  }

  function redo() {
    if (canRedo.value) {
      historyIndex.value++
      const state = JSON.parse(history.value[historyIndex.value])
      previewComponents.value = state.previewComponents
      pageConfig.value = state.pageConfig
    }
  }

  return {
    components,
    previewComponents,
    nowComponent,
    pageConfig,
    getComponentsByCategory,
    nowComponentsData,
    updateNowComponents,
    deleteComponent,
    history,
    historyIndex,
    addHistory,
    undo,
    redo,
    canUndo,
    canRedo,
  }
})
